using System.Text.Json;
using System.Text;
using System.Text.Encodings.Web;
using MauiApp.Services;

namespace MauiApp.Services
{
    /// <summary>
    /// JSON处理助手类，提供JSON序列化和转义功能
    /// </summary>
    public static class JsonHelper
    {
        /// <summary>
        /// 序列化对象为JSON字符串，包含适当的转义处理
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">要序列化的对象</param>
        /// <returns>序列化后的JSON字符串</returns>
        public static string Serialize<T>(T obj)
        {
            try
            {
                var options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true,
                    WriteIndented = true,
                    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                };
                return JsonSerializer.Serialize(obj, options);
            }
            catch (Exception ex)
            {
                LogHelper.Error($"JSON序列化失败: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 反序列化JSON字符串为对象
        /// </summary>
        /// <typeparam name="T">目标对象类型</typeparam>
        /// <param name="jsonString">JSON字符串</param>
        /// <returns>反序列化后的对象</returns>
        public static T Deserialize<T>(string jsonString)
        {
            try
            {
                var options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                };
                return JsonSerializer.Deserialize<T>(jsonString, options);
            }
            catch (Exception ex)
            {
                LogHelper.Error($"JSON反序列化失败: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 对字符串进行JSON转义，用于前端显示或传输
        /// </summary>
        /// <param name="input">需要转义的字符串</param>
        /// <returns>转义后的字符串</returns>
        public static string EscapeJson(string input)
        {
            if (string.IsNullOrEmpty(input))
                return input;

            try
            {
                // 使用JSON序列化来确保正确转义
                return Serialize(input).Trim('"');
            }
            catch (Exception ex)
            {
                LogHelper.Error($"JSON转义失败: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 反转义JSON字符串
        /// </summary>
        /// <param name="escapedJson">已转义的JSON字符串</param>
        /// <returns>反转义后的原始字符串</returns>
        public static string UnescapeJson(string escapedJson)
        {
            if (string.IsNullOrEmpty(escapedJson))
                return escapedJson;

            try
            {
                // 为了使用Deserialize方法，需要将字符串包装在引号中
                string wrappedJson = $"\"{escapedJson}\"";
                return Deserialize<string>(wrappedJson);
            }
            catch (Exception ex)
            {
                LogHelper.Error($"JSON反转义失败: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 格式化JSON字符串，使其更易读
        /// </summary>
        /// <param name="jsonString">原始JSON字符串</param>
        /// <returns>格式化后的JSON字符串</returns>
        public static string FormatJson(string jsonString)
        {
            if (string.IsNullOrEmpty(jsonString))
                return jsonString;

            try
            {
                var obj = JsonDocument.Parse(jsonString);
                using (var stream = new System.IO.MemoryStream())
                using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))
                {
                    obj.WriteTo(writer);
                    writer.Flush();
                    return System.Text.Encoding.UTF8.GetString(stream.ToArray());
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"JSON格式化失败: {ex.Message}");
                throw;
            }
        }
    }
}